package com.xingli.jingdongshop.controller;

import com.xingli.jingdongshop.beans.RedeemStatusEnums;
import com.xingli.jingdongshop.dao.RedeemDao;
import com.xingli.jingdongshop.entity.Redeem;
import com.xingli.jingdongshop.proto.MsgJinDouShop;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.Base64;
import java.util.List;

@Controller
@RequestMapping("/jd/redeem")
public class RedeemController {


    @Autowired
    private RedeemDao redeemDao;

    /**
     * 玩家购买兑换码
     * @param goodsId
     * @param playId
     * @return
     */
    @ResponseBody
    @PostMapping(value = "/goods",produces = {"application/x-protobuf;charset=UTF-8"})
    public Object getRedeem(int goodsId,int playId,String uuid){
        MsgJinDouShop.ResRedeem.Builder resp = MsgJinDouShop.ResRedeem.newBuilder();
        resp.setRedeem("");
        resp.setPlayerId(playId);
        resp.setGoodsId(goodsId);
        resp.setReqUuid(uuid);
        synchronized (this){
            List<Redeem> list = redeemDao.findByGoodsIdAndStatus(goodsId, RedeemStatusEnums.NotRedeemed);
            if (list.size() == 0){
                resp.setErrNo(1);
                resp.setErrMsg("not enough");
            }else {
                Redeem redeem = list.get(0);
                redeem.setPlayId(playId);
                redeem.setStatus(RedeemStatusEnums.Received);
                redeemDao.save(redeem);
                resp.setRedeem(redeem.getRedeemCode());
                resp.setErrNo(0);
                resp.setErrMsg("suc");
            }
        }

        String str = Base64.getEncoder().encodeToString(resp.build().toByteArray());
        return Base64.getEncoder().encodeToString(resp.build().toByteArray());
    }

    /**
     * 获取兑换码的状态
     * @param playId
     * @param redeemList
     * @return
     */
    @ResponseBody
    @PostMapping(value = "/status",produces = {"application/x-protobuf;charset=UTF-8"})
    public Object getRedeemStatus(int playId,String[] redeemList){
//        List<Redeem> redeems = redeemDao.findByRedeemCodeIn(redeemList);
//        MsgJinDouShop.ResRedeemStatus.Builder res = MsgJinDouShop.ResRedeemStatus.newBuilder();
//        res.setPlayerId(playId);
//        for (int i = 0; i < redeems.size(); i++) {
//            MsgJinDouShop.RedeemStatus.Builder redeemStatus = MsgJinDouShop.RedeemStatus.newBuilder();
//            redeemStatus.setStatus(redeems.get(i).getStatus().ordinal());
//            redeemStatus.setRedeem(redeems.get(i).getRedeemCode());
//            res.addStatusList(i,redeemStatus);
//        }
//        return res.build();
    return null;
    }



}
